package com.wanyu.video.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class GroupChatClient {


    private static final String HOST = "127.0.0.1";

    private static final int PORT = 6666;

    private Selector selector;

    private SocketChannel channel;

    private String username;


    public GroupChatClient() throws IOException {
        // 初始化选择器
        selector = Selector.open();

        //初始化channel，连接对应地址的服务端，并设置非阻塞
        channel = (SocketChannel) SocketChannel.open(new InetSocketAddress(HOST, PORT)).configureBlocking(false);
        // 通道注册监听read事件
        channel.register(selector, SelectionKey.OP_READ);
        username = channel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok");
    }

    public void sendInfo(String info){
        info = username + " 说 " + info;

        try {
            channel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readInfoFromServer(){

        try {
            // 获取消息
            int read = selector.select();
            if(read > 0){
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {

                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        // 从缓冲区中读取数据
                        socketChannel.read(byteBuffer);
                        System.out.println(new String(byteBuffer.array()));
                    }
                }
                iterator.remove();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public static void main(String[] args) throws IOException {

        // 启动客户端
        GroupChatClient groupChatClient = new GroupChatClient();

        new Thread(()->{
            while(true){
                groupChatClient.readInfoFromServer();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()){
            String msg = scanner.nextLine();
            groupChatClient.sendInfo(msg);
        }

    }
}
